﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MVCExtension.FrameWork
{
    /// <summary>
    /// 缓存统一管理
    /// </summary>
    public class CacheHelper
    {
        public static readonly int seconds = 5;//默认缓存保留2秒钟
        /// <summary>
        /// 添加一项Cache
        /// </summary>
        /// <param name="key">Cache标志</param>
        /// <param name="value">Cache具体内容</param>
        /// <returns></returns>
        public static void AddStringCache ( string key , string value )
        {

            HttpRuntime.Cache.Insert ( key , value , null , DateTime.UtcNow.AddSeconds ( seconds ) , TimeSpan.Zero );

        }

        public static void AddObjectCache(string key, object value)
        {

            HttpRuntime.Cache.Insert(key, value, null, DateTime.UtcNow.AddSeconds(seconds), TimeSpan.Zero);

        }

        public static void AddObjectCache(string key, object value,bool Keep)
        {
            if (Keep)
            {
                HttpRuntime.Cache.Insert(key, value);
            }
            else
            {
                AddObjectCache(key, value);
            }
        }
        /// <summary>
        /// 获取一个Cache
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>缓存的内容</returns>
        public static string GetStringCache ( string key )
        {
            return HttpRuntime.Cache.Get ( key ).ToString ( );
        }
        public static Object GetObjectCache ( string key )
        {
            return HttpRuntime.Cache.Get ( key );
        }



        /// <summary>
        /// 判断指定的缓存是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExits ( string key )
        {


            return HttpRuntime.Cache.Get ( key ) != null;

        }
        /// <summary>
        /// 删除所有的缓存数据
        /// </summary>
        public static void RemoveAllCache ( )
        {
            System.Collections.IDictionaryEnumerator ss = HttpRuntime.Cache.GetEnumerator ( );


            while ( ss.MoveNext ( ) )
            {

                try
                {
                    HttpRuntime.Cache.Remove ( ss.Key.ToString ( ) );
                }
                catch { }
            }

        }
    }

}
